const container = document.querySelector('body')
let observer
let waterMarkEle
let observed = false
let watermarkText

const initObserver = () => {
    if (!observer) {
        const style = waterMarkEle.getAttribute('style')
        const callback = function (mutationsList, observer) {
            // Use traditional 'for loops' for IE 11
            for (const mutation of mutationsList) {
                mutation.removedNodes.forEach(function (ele) {
                    if (ele === waterMarkEle) {
                        container.appendChild(waterMarkEle)
                    }
                })
                if (
                    mutation.type === 'attributes' &&
                    mutation.target === waterMarkEle &&
                    waterMarkEle.getAttribute('style') !== style
                ) {
                    waterMarkEle.setAttribute('style', style)
                }
            }
        }
        observer = new MutationObserver(callback)
    }
}

function createWatermark() {
    if (!waterMarkEle) {
        const angle = -30
        let canvas = document.createElement('canvas')
        canvas.width = 300
        canvas.height = 300
        const ctx = canvas.getContext('2d')
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.fillStyle = '#000'
        ctx.globalAlpha = 0.1
        ctx.font = '20px serif'
        ctx.rotate((Math.PI / 180) * angle)
        ctx.fillText(watermarkText, 0, canvas.height - canvas.height / 4)

        waterMarkEle = document.createElement('div')
        waterMarkEle.setAttribute(
            'style',
            `background-image:url(${canvas.toDataURL()});position:fixed;z-index:99999;left:8px;right:8px;top:8px;bottom:8px;pointer-events: none;background-repeat: repeat;background-size:${
                canvas.width
            }px; `
        )
        canvas = null
    }
}

export function useWaterMark(text) {
    if(watermarkText) {
        text= watermarkText
    } else {
        watermarkText = text
    }
    if (observed) {
        return
    }
    createWatermark()
    container.appendChild(waterMarkEle)
    initObserver()

    observer.observe(container, { attributes: true, childList: true, subtree: true })
    observed = true
}

export function stopUseWaterMark() {
    if (observed) {
        observer.disconnect()
        container.removeChild(waterMarkEle)
    }
    observed = false
}
